package com.guqj.mq.rabbitmq;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class RabbitUtil {
	
	
	public static Connection getConnection(String userName, String password, String virtualHost, String hostName, int portNumber) throws IOException, TimeoutException{
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUsername(userName);
		factory.setPassword(password);
		factory.setVirtualHost(virtualHost);
		factory.setHost(hostName);
		factory.setPort(portNumber);
		return factory.newConnection();
	}
	
	
	public static Connection getConnection2(String userName, String password, String virtualHost, String hostName, int portNumber){
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setUri("amqp://" + userName + ":" + password +"@" + hostName + ":" + portNumber + "/" + virtualHost);
			return factory.newConnection();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void createChannel(Connection conn, Channel channel){
		try {
			// 建立连接
			conn = RabbitUtil.getConnection(RabbitConfig.USERNAME, RabbitConfig.PASSWORD, RabbitConfig.VHOST,
					RabbitConfig.HOST, RabbitConfig.PORT);
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
	}
	
	
	public static Channel createChannel(Connection conn){
		if(conn == null){
			return null;
		}
		// 创建通道
		try {
			Channel channel = conn.createChannel();
			channel.exchangeDeclare(RabbitConfig.EXCHANGENAME, "direct", true);
			/*
			 * String queueName = channel.queueDeclare().getQueue();
			 * channel.queueBind(queueName, exchangeName, "");
			 */
			// 创建队列
			channel.queueDeclare(RabbitConfig.QUEUENAME, true, false, false, null);
			// 队列绑定至路由
			channel.queueBind(RabbitConfig.QUEUENAME, RabbitConfig.EXCHANGENAME, RabbitConfig.ROUTEINGKEY);
			return channel;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static void close(Connection conn, Channel channel){
		try {
			if (channel != null) {
				channel.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
	}
}
